from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=True, index=True, nullable=False)
    password_hash = Column(String(255), nullable=False)
    role = Column(String(20), default="user", nullable=False)  # admin 或 user
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())

    # 关系
    data_sources = relationship("DataSource", back_populates="user")
    email_tasks = relationship("EmailTask", back_populates="user")
    contacts = relationship("Contact", back_populates="user")
    contact_groups = relationship("ContactGroup", back_populates="user")
    email_configs = relationship("EmailConfig", back_populates="user")
    email_templates = relationship("EmailTemplate", back_populates="user")

    def __repr__(self):
        return f"<User(id={self.id}, username='{self.username}', role='{self.role}')>"
